package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.DownloadFileUtil;
import com.molichuxing.gateway.api.config.OptionalLogConfig;
import com.molichuxing.gateway.api.services.StatisticsApiService;
import com.molichuxing.gateway.bff.statistics.entity.response.*;
import com.molichuxing.gateway.bff.statistics.services.StatisticsBffService;
import com.molichuxing.gateway.bff.statistics.services.StatisticsExportService;
import com.molichuxing.gateway.utils.PoiExcelUtil;
import com.molichuxing.services.property.OrderTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 16:06 2019/10/14
 * @Modified By:
 **/
@Api(tags = "统计相关接口")
@RestController
@RequestMapping(value = "/statistics")
public class StatisticsApiServiceImpl implements StatisticsApiService {
    private static final Logger logger = LoggerFactory.getLogger(StatisticsApiServiceImpl.class);

    @Resource
    private StatisticsBffService statisticsBffService;

    @Resource
    private StatisticsExportService statisticsExportService;


    @Override
    @ApiOperation(value = "首页订单统计")
    @GetMapping(value = "/home/order")
    public ResponseResult<HomeOrderStatisticsVo> getHomeOrderStatisticsVo() {
        ResponseResult<HomeOrderStatisticsVo> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getHomeOrderStatisticsVo());
        } catch (Exception e) {
            // 记录异常，返回异常信息
            logger.error("[getHomeOrderStatisticsVo]首页订单统计异常", e);
            result.error("首页订单统计异常");
        }
        return result;
    }


    @Override
    @ApiOperation(value = "资源统计")
    @GetMapping(value = "/resource")
    public ResponseResult<ResourceStatisticsVo> getResourceStatisticsVo() {
        ResponseResult<ResourceStatisticsVo> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getResourceStatisticsVo());
        } catch (Exception e) {
            // 记录异常，返回异常信息
            logger.error("[getResourceStatisticsVo]资源统计异常", e);
            result.error("资源统计异常");
        }
        return result;
    }


    @Override
    @ApiOperation(value = "订单统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderType", value = "订单类型（1：订阅，2：专属）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "queryType", value = "查询类型（1：以往，2：今日）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "startTime", value = "自定义开始时间（%Y-%m-%d）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "自定义结束时间（%Y-%m-%d）", required = false, dataType = "String")

    })
    @GetMapping(value = "/order")
    public ResponseResult<PreviousOrderStatisticsVo> getOrderStatisticsVo(@RequestParam Map<String, Object> map) {
        ResponseResult<PreviousOrderStatisticsVo> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getOrderStatisticsVo(map));
        } catch (Exception e) {
            // 记录异常，返回异常信息
            logger.error("[getPreviousOrderStatisticsVo]订单统计异常", e);
            result.error("订单统计异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "违章统计")
    @GetMapping(value = "/violation")
    public ResponseResult<ViolationCountVo> getViolationStatisticsVo() {
        ResponseResult<ViolationCountVo> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getViolationStatisticsVo());
        } catch (Exception e) {
            logger.error("[getViolationStatisticsVo]违章统计异常", e);
            result.error("违章统计异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "待处理事务统计")
    @GetMapping(value = "/pend")
    public ResponseResult<PendStatisticsVo> getPendStatisticsVo() {
        ResponseResult<PendStatisticsVo> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getPendStatisticsVo());
        } catch (Exception e) {
            logger.error("[getPendStatisticsVo]待处理事务统计异常", e);
            result.error("待处理事务统计异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "风险统计")
    @GetMapping(value = "/risk")
    public ResponseResult<RiskStatisticsVo> getRiskStatisticsVo() {
        ResponseResult<RiskStatisticsVo> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getRiskStatisticsVo());
        } catch (Exception e) {
            logger.error("[getRiskStatisticsVo]风险统计异常", e);
            result.error("风险统计异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "订单地域分布统计")
    @GetMapping(value = "/distribution")
    public ResponseResult<List<DistributionStatisticsVo>> getOrderRegionalDistribution() {
        ResponseResult<List<DistributionStatisticsVo>> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getOrderRegionalDistribution());
        } catch (BizException e) {
            logger.error("[getOrderRegionalDistribution]查询订单地域分布统计信息异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getOrderRegionalDistribution]查询订单地域分布统计信息异常", e);
            result.error("查询订单地域分布统计信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "车型销售统计")
    @GetMapping(value = "/vehicle/sales")
    public ResponseResult<List<SalesStatisticsVo>> getOrderVehicleSales() {
        ResponseResult<List<SalesStatisticsVo>> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getOrderVehicleSales());

        } catch (BizException e) {
            logger.error("[getOrderVehicleSales]查询车型销售统计信息异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getOrderVehicleSales]查询车型销售统计信息异常", e);
            result.error("查询车型销售统计信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "商品销售统计 (专属、订阅)")
    @ApiImplicitParam(name = "orderType", value = "订单类型（1：订阅，2：专属）", required = true, dataType = "Integer")
    @GetMapping(value = "/goods/sales")
    public ResponseResult<List<SalesStatisticsVo>> getOrderGoodsSales(@RequestParam Integer orderType) {
        ResponseResult<List<SalesStatisticsVo>> result = new ResponseResult<>();
        OrderTypeEnum orderTypeEnum = null;
        try {
            orderTypeEnum = orderType == 1 ? OrderTypeEnum.SUBSCRIBE : orderType == 2 ? OrderTypeEnum.EXCLUSIVEL : null;
            result.success(statisticsBffService.getOrderGoodsSales(orderTypeEnum));
        } catch (BizException e) {
            logger.error("[getOrderVehicleSales]查询商品销售统计信息异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getOrderVehicleSales]查询商品销售统计信息异常", e);
            result.error("查询商品销售统计信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "订单用户画像 (性别分布、年龄分布)")
    @GetMapping(value = "/user/portrait")
    public ResponseResult<OrderUserPortraitVo> getOrderUserPortrait() {
        ResponseResult<OrderUserPortraitVo> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getOrderUserPortrait());
        } catch (BizException e) {
            logger.error("[getOrderVehicleSales]订单用户画像信息异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getOrderVehicleSales]订单用户画像信息异常", e);
            result.error("查询订单用户画像信息异常");
        }
        return result;
    }


    @Override
    @ApiOperation(value = "资产统计")
    @GetMapping(value = "/asset/query")
    public ResponseResult<AssetCountVo> getAssetCount() {
        ResponseResult<AssetCountVo> result = new ResponseResult<>();
        try {
            result.success(statisticsBffService.getAssetCount());
        } catch (BizException e) {
            logger.error("[getAssetCount]查询资产统计信息异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getAssetCount]查询资产统计信息异常", e);
            result.error("查询资产统计信息异常");
        }
        return result;
    }


    @Override
    @ApiOperation(value = "资产统计-导出")
    @GetMapping(value = "/asset/download")
    @OptionalLogConfig(methods="资产统计-导出")
    public void getAssetCountDownload(HttpServletRequest request, HttpServletResponse response) {
        try {

            String fileName = "监控表(" + DateUtil.formatDate(LocalDate.now()) + ").xlsx";
            // 生成excel
            XSSFWorkbook xssBook = statisticsExportService.buildWorkbook();
            // 下载
            DownloadFileUtil.downloadExcel(request, response, fileName, xssBook);
        } catch (BizException e) {
            logger.error("[getCarListDownload]监控表导出异常:", e);
        } catch (Exception e) {
            logger.error("[getCarListDownload]监控表导出异常:", e);
        }
    }

}
